const express = require('express'),
    router = express.Router()
const async = require('async')
const crypto = require('crypto')
const request = require('request')
const xmlParse = require('xml2js').parseString
const moment = require('moment');
const newLine = '\n'

const SMSQQ = require('../../util/businessUtil/smsQQ.js')

var appID = "wxaa38ff0084aa64af";
var appsecret = "7eab80c43a697de6c0642a6612f84c65";
var account = "gh_dd8c2ff1cac5"

// var appID = 'wx6c747a24bcf27a67'
// var appsecret = '3e2a220250feadbde0747fe8fe73e608'
// var account = 'gh_a50a502213f4'
const token = 'yifeitoken';


const LogUtil = require('../../util/baseUtil/LogUtil')


//var io = require('socket.io').listen(server);
// configuration ===============================================================

// redisClient = redis.createClient({host : 'localhost', port : 6379});

function addZero(a) {
    if (a < 10) {
        return '0' + a
    } else {
        return a
    }
}
module.exports = {

    refreshToken: async(req, res, next) => {
        getAccessTokenFromWeb(function(e) {
            res.send(token)
        })

    },
    xx: async(req, res, next) => {
        getToken(function(access_token) {
            // createMenu(access_token)
            // getTags(access_token)
            createMenu(access_token)
            creatConditionalMenu(access_token)
        })
    },
    checkService: async(req, res, next) => {
        getToken(function(access_token) {
            // createMenu(access_token)
            // getTags(access_token)
            creatConditionalMenu(access_token)
        })
        try {
            const { signature, timestamp, nonce, echostr } = req.query
            let chechkArray = [token, timestamp, nonce].sort()
            let hash = crypto.createHash('sha1')
            hash.update(chechkArray.join(''))
            const hashCode = hash.digest('hex')
            if (hashCode === signature) {
                res.send(echostr)
                getToken(function(access_token) {
                    // createMenu(access_token)
                    // getTags(access_token)
                    creatConditionalMenu(access_token)
                })
            } else {
                res.send({ 'code': 401 })
            }
        } catch (e) {
            next(e)
        }
    },
    postToDO: async(req, res, next) => {
        console.log(req.body, 'jgjgj')
        var that = this
        let data = ''
        req.on('data', function(chuck) {
            data += chuck
        })
        req.on('end', () => {
            xmlParse(data, (err, result) => {
                console.log(err, result, 'blasd')
                let account = result['xml'].ToUserName
                let fromuser = result['xml'].FromUserName
                let msgtype = result['xml'].MsgType
                let event = result['xml'].Event
                let eventKey = result['xml'].EventKey
                let content = result['xml'].Content
                WechatPublicUser.findOne({ openid: fromuser }, '_id').exec(function(err, data) {
                    if (data == null) {
                        getUserInfo(fromuser)
                    } else {
                        if (eventKey == 'cellphone_bind') {
                            WechatPublicUser.findOne({ openid: fromuser }, 'cellphone').exec(function(err, wechatUser) {
                                if (wechatUser.cellphone == null) {
                                    redisClient.del(fromuser)
                                    redisClient.hmset(fromuser[0], { 'state': 0 }, function(err, data) {
                                        let xml = generateXMLMessage(fromuser, 'text', "请输入手机号")
                                        res.send(xml)
                                    })
                                } else {
                                    let xml = generateXMLMessage(fromuser, 'text', "已绑定过手机")
                                    res.send(xml)
                                }
                            })
                        } else if (eventKey == 'classDetail') {
                            WechatPublicUser.findOne({ openid: fromuser }, 'parents student cellphone').exec(function(err, parents) {
                                if (parents == null) {
                                    let xml = generateXMLMessage(fromuser, 'text', "请先绑定手机")
                                    res.send(xml)
                                    return false
                                } else if (parents.cellphone == null) {
                                    let xml = generateXMLMessage(fromuser, 'text', "请先绑定手机")
                                    res.send(xml)
                                    return false
                                }
                                Parents.find({ cellphone: parents.cellphone }, function(err, datax) {
                                    let message = ''
                                    let students = datax.map(function(e) { return e.student })
                                    CourseOrder.find({ student: { $in: students }, isDelete: 0, $or: [{ 'numberOfClasses': { $gt: 0 } }, { 'numberOfHours': { $gt: 0 } }, { 'numberOfMonths': { $gt: 0 } }] })
                                        .populate({ path: 'course', select: 'name' }).populate({ path: 'class' }).populate({ path: 'student' }).sort({ createdAt: -1 }).exec(function(err, courseData) {
                                            if (courseData.length > 0) {
                                                courseData.forEach(e => {

                                                    let tempText = e.student.name + '  课程：' + e.course.name + '  班级:' + (e.class == undefined ? '暂无' : e.class.name) + newLine
                                                    message += tempText
                                                })
                                                let xml = generateXMLMessage(fromuser, 'text', message)
                                                res.type('xml')
                                                res.send(xml)
                                            } {
                                                let xml = generateXMLMessage(fromuser, 'text', "未找到信息，请与我们联系")
                                                res.send(xml)
                                            }
                                        })

                                })
                            })

                        } else if (eventKey == 'rollCallDetail') {
                            WechatPublicUser.findOne({ openid: fromuser }, 'parents student cellphone').exec(function(err, user) {
                                if (user == null) {
                                    let xml = generateXMLMessage(fromuser, 'text', "请先绑定手机")
                                    res.send(xml)
                                    return false
                                } else if (user.cellphone == null) {
                                    let xml = generateXMLMessage(fromuser, 'text', "请先绑定手机")
                                    res.send(xml)
                                    return false
                                }

                                Parents.find({ cellphone: user.cellphone }, 'student').exec(function(err, student) {
                                    let students = student.map(function(e) { return e.student[0] })
                                    if (students.length == 0) {
                                        let xml = generateXMLMessage(fromuser, 'text', "未找到信息，请与我们联系")
                                        res.send(xml)
                                        return false
                                    }
                                    StudentRecord.find({ student: students }, 'student class createAt').populate('student class', 'name').limit(10).exec(function(err, studentRecords) {
                                        if (studentRecords.length == 0) {
                                            let xml = generateXMLMessage(fromuser, 'text', '没有上课记录')
                                            res.send(xml)
                                            return false
                                        }
                                        let text = ""
                                        for (let i = 0; i < studentRecords.length; i++) {
                                            console.log(studentRecords[i], 'dsd')
                                            if (studentRecords[i].student != null && studentRecords[i].class != null) {
                                                text += '姓名：' + studentRecords[i].student.name + newLine + '课程：' + studentRecords[i].class.name + newLine + '时间：' + moment(studentRecords[i].createAt).format('YYYY-MM-DD HH:mm') + newLine + newLine
                                            }
                                        }
                                        if (text == "") {
                                            text = "您的上课信息错误，请与我们联系查询"
                                        }
                                        let xml = generateXMLMessage(fromuser, 'text', text)
                                        res.send(xml)
                                    })
                                })

                            })
                        } else if (eventKey == 'remainder') {
                            WechatPublicUser.findOne({ openid: fromuser }, 'parents student cellphone').exec(function(err, wechatUser) {
                                if (wechatUser == null) {
                                    let xml = generateXMLMessage(fromuser, 'text', "请先绑定手机")
                                    res.send(xml)
                                    return false
                                } else if (wechatUser.cellphone == null) {
                                    let xml = generateXMLMessage(fromuser, 'text', "请先绑定手机")
                                    res.send(xml)
                                    return false
                                }

                                Parents.find({ cellphone: wechatUser.cellphone }).exec(function(err, student) {
                                    let students = student.map(function(e) { return e.student[0] })
                                    if (students.length == 0) {
                                        let xml = generateXMLMessage(fromuser, 'text', "未找到信息，请与我们联系")
                                        res.send(xml)
                                        return false
                                    }
                                    CourseOrder.find({ student: { $in: students }, isDelete: 0, $or: [{ 'numberOfClasses': { $gt: 0 } }, { 'numberOfHours': { $gt: 0 } }, { 'numberOfMonths': { $gt: 0 } }] })
                                        .populate({ path: 'course', select: 'name' }).populate({ path: 'class' }).populate({ path: 'student' }).sort({ createdAt: -1 }).exec(function(err, courseData) {
                                            let text = ''
                                            if (courseData.length == 0) {
                                                let xml = generateXMLMessage(fromuser, 'text', "没有课程信息")
                                                res.send(xml)
                                                return false
                                            }
                                            courseData.forEach(e => {
                                                let method = ''
                                                let left = ''
                                                let start = ''
                                                let valid = ''
                                                if (e.type == 0) {
                                                    method = '课时'
                                                    left = e.numberOfClasses
                                                } else if (e.type == 1) {
                                                    method = '小时'
                                                    left = e.numberOfHours
                                                } else if (e.type == 2) {
                                                    method = '包月'
                                                    left = e.numberOfMonths
                                                    start = moment(e.startDate).format('YYYY-MM-DD')
                                                }
                                                if (e.valid) {
                                                    valid = moment(e.validDate).format('YYYY-MM-DD')
                                                }
                                                text += '姓名：' + e.student.name + newLine + '付费方式: ' + method + newLine
                                                text += '余额：' + left + newLine
                                                text += start == '' ? '' : ('开始日期： ' + start + newLine)
                                                text += valid == '' ? '' : ('有效截止： ' + valid + newLine)
                                                text += newLine


                                            })
                                            let xml = generateXMLMessage(fromuser, 'text', text)
                                            res.send(xml)

                                        })

                                })



                            })

                        } else if (eventKey == 'history') {
                            let xml = generateXMLMessage(fromuser, 'text', '目前没有')
                            res.send(xml)
                        } else if (eventKey == 'contactUs') {
                            let xml = generateXMLMessage(fromuser, 'text', '电话：18588888888')
                            res.send(xml)
                        } else if (eventKey == 'askLeave') {
                            WechatPublicUser.findOne({ openid: fromuser }, 'parents student cellphone').exec(function(err, wechatUser) {
                                if (wechatUser == null) {
                                    let xml = generateXMLMessage(fromuser, 'text', "请先绑定手机")
                                    res.send(xml)
                                    return false
                                } else if (wechatUser.cellphone == null) {
                                    let xml = generateXMLMessage(fromuser, 'text', "请先绑定手机")
                                    res.send(xml)
                                    return false

                                }

                                Parents.find({ cellphone: wechatUser.cellphone }).exec(function(err, student) {
                                    let students = student.map(function(e) { return e.student[0] })
                                    if (students.length == 0) {
                                        let xml = generateXMLMessage(fromuser, 'text', "未找到信息，请与我们联系")
                                        res.send(xml)
                                        return false
                                    }
                                    Student.find({ _id: students, isDelete: 0 }, 'name').sort({ 'createdAt': -1 }).exec(function(err, studentsx) {
                                        let temp = '请选择学生，回复数字' + newLine + newLine
                                        for (var i = 0; i < studentsx.length; i++) {
                                            temp += String(i + 1) + '.  ' + studentsx[i].name + newLine
                                        }
                                        let xml = generateXMLMessage(fromuser, 'text', temp)
                                            //set redis
                                        redisClient.hmset(fromuser[0], { 'leaveState': 0 }, function(err, data) {
                                            res.send(xml)
                                        })
                                    })
                                })
                            })
                        } else if (eventKey == 'report') {
                            WechatPublicUser.findOne({ openid: fromuser }, 'parents student cellphone').exec(function(err, wechatUser) {
                                if (wechatUser == null) {
                                    let xml = generateXMLMessage(fromuser, 'text', "请先绑定手机")
                                    res.send(xml)
                                    return false
                                } else if (wechatUser.cellphone == null) {
                                    let xml = generateXMLMessage(fromuser, 'text', "请先绑定手机")
                                    res.send(xml)
                                    return false

                                }

                                Parents.find({ cellphone: wechatUser.cellphone }).exec(function(err, student) {
                                    let students = student.map(function(e) { return e.student[0] })
                                    if (students.length == 0) {
                                        let xml = generateXMLMessage(fromuser, 'text', "未找到信息，请与我们联系")
                                        res.send(xml)
                                        return false
                                    }

                                    StudentStudyPlan.find({ student: { $in: students } }, 'name createdAt student').populate({ path: 'student', select: 'name' }).sort({ 'createdAt': -1 }).limit(9).exec(function(err, studentsx) {
                                        console.log(studentsx, 'dadsa')
                                        let temp = '请选择学生报告，回复数字' + newLine + newLine
                                        for (var i = 0; i < studentsx.length; i++) {
                                            let date = new Date(studentsx[i].createdAt)
                                            date = date.getFullYear() + '-' + addZero(date.getMonth() + 1) + '-' + addZero(date.getDate())
                                            temp += String(i + 1) + '.  ' + studentsx[i].student.name + '  (' + date + ')' + newLine
                                        }
                                        let xml = generateXMLMessage(fromuser, 'text', temp)
                                            //set redis
                                        redisClient.del(fromuser[0], function(err) {
                                            redisClient.hmset(fromuser[0], { 'reportState': 0 }, function(err, data) {

                                                res.send(xml)
                                            })
                                        })

                                    })
                                })
                            })
                        } else if (msgtype == 'text') {
                            let content = result['xml'].Content
                            redisClient.hgetall(fromuser, function(err, data) { // cellphone verification   , if state is 0 , get cellphone, if state is 1 , get verification , if done, remove
                                if (data != null) {
                                    console.log(data)
                                    if (data.state == 0) {
                                        if (validateCellphone(content)) {
                                            let code = creatValidateCellphoneCode()
                                            var temp = { state: 1, code: code, cellphone: content[0] }
                                            var xml = generateXMLMessage(fromuser, 'text', '验证码已经以短信形式发送至您手机号，请输入验证码绑定手机')
                                                // send verification
                                            SMSQQ.sendVerification(code, content[0], function(err, response, resData) {
                                                if (resData.errmsg == 'OK') {
                                                    redisClient.hmset(fromuser[0], temp, function(err, success) {
                                                        res.send(xml)
                                                    })
                                                } else {
                                                    var xml2 = generateXMLMessage(fromuser, 'text', '出错了，请联系管理员')
                                                    res.send(xml2)
                                                }
                                            })

                                        } else {
                                            var xml = generateXMLMessage(fromuser, 'text', '手机输入错误')
                                            res.send(xml)
                                        }
                                    } else if (data.state == 1) {
                                        if (data.code == content) {
                                            // new user update
                                            WechatPublicUser.findOne({ openid: fromuser }).exec(function(err, user) {
                                                Parents.find({ cellphone: data.cellphone }, '_id student').exec(function(err, parents) {
                                                    if (parents.length == 0) {
                                                        Student.find({ cellphone: data.cellphone }, '_id').exec(function(err, student) {
                                                            if (student.length == 0) {
                                                                var xml = generateXMLMessage(fromuser, 'text', '未发现与该手机号相关的用户，请联系我们')
                                                                res.send(xml)
                                                                return false
                                                            }
                                                            user.student = student.map(e => { return e._id })
                                                            user.cellphone = data.cellphone
                                                            user.save(function(err, userSave) {
                                                                var xml = generateXMLMessage(fromuser, 'text', '学生绑定成功')
                                                                    //设置用户标签
                                                                res.send(xml)
                                                            })
                                                            redisClient.del(fromuser)
                                                        })
                                                        return false
                                                    }
                                                    user.parents = parents.map(e => { return e._id })
                                                    user.cellphone = data.cellphone
                                                    user.save(function(err, userSave) {
                                                        var xml = generateXMLMessage(fromuser, 'text', '家长绑定成功')
                                                            //设置用户标签
                                                        res.send(xml)
                                                    })
                                                    redisClient.del(fromuser)
                                                })
                                            })

                                        } else {
                                            var xml = generateXMLMessage(fromuser, 'text', '验证码输入错误')
                                            res.send(xml)
                                        }
                                    } else if (data.leaveState == 0) {
                                        content = content[0]
                                        if (!parseInt(content)) {
                                            var xml = generateXMLMessage(fromuser, 'text', '请输入数字')
                                            res.send(xml)
                                        } else {
                                            let index = parseInt(content) - 1
                                            WechatPublicUser.findOne({ openid: fromuser }).exec(function(err, user) {
                                                Parents.find({ cellphone: user.cellphone }, '_id student').exec(function(err, parentData) {
                                                    let students = parentData.map(function(e) { return e.student[0] })
                                                    Student.find({ _id: students, isDelete: 0 }, '_id').sort({ createdAt: -1 }).exec(function(err, studentx) {
                                                        console.log(studentx, 'xxx', students)
                                                        if (studentx.length < index) {
                                                            var xml = generateXMLMessage(fromuser, 'text', '请输入对应学生数字')
                                                            res.send(xml)
                                                        } else {
                                                            let theStudent = studentx[index]
                                                            CourseOrder.find({ student: theStudent, isDelete: 0, $or: [{ 'numberOfClasses': { $gt: 0 } }, { 'numberOfHours': { $gt: 0 } }, { 'numberOfMonths': { $gt: 0 } }], class: { $ne: null } })
                                                                .populate({ path: 'course', select: 'name' }).populate({ path: 'class' }).populate({ path: 'student' }).sort({ createdAt: -1 }).exec(function(err, courseData) {
                                                                    if (courseData.length == 0) {
                                                                        var xml = generateXMLMessage(fromuser, 'text', '该学生没有当前课程信息')
                                                                        res.send(xml)
                                                                        return false
                                                                    } else {
                                                                        let message = '请输入对应数字，选择请假课程' + newLine + newLine
                                                                        let datalist = []
                                                                        for (var i = 0; i < courseData.length; i++) {
                                                                            if (datalist.indexOf(courseData[i].course._id) == -1) {
                                                                                message += String(i + 1) + '.  ' + courseData[i].course.name + '(' + courseData[i].class.name + ')' + newLine
                                                                                datalist.push(courseData[i].course._id)
                                                                            }
                                                                        }
                                                                        redisClient.hmset(fromuser[0], { 'leaveState': 1, student: String(theStudent._id) }, function(err, data) {
                                                                            var xml = generateXMLMessage(fromuser, 'text', message)
                                                                            res.send(xml)
                                                                            return false
                                                                        })

                                                                    }
                                                                })
                                                        }
                                                    })
                                                })
                                            })

                                        }
                                    } else if (data.leaveState == 1) {
                                        content = content[0]
                                        if (!parseInt(content)) {
                                            var xml = generateXMLMessage(fromuser, 'text', '请输入数字')
                                            res.send(xml)
                                        } else {
                                            let index = parseInt(content) - 1
                                            let theStudent = data.student

                                            Student.findOne({ _id: theStudent }).exec(function(err, theStudent) {
                                                if (theStudent == null) {
                                                    redisClient.del(fromuser)
                                                    var xml = generateXMLMessage(fromuser, 'text', '出错了,请重试')
                                                    res.send(xml)
                                                } else {
                                                    CourseOrder.find({ student: theStudent, isDelete: 0, $or: [{ 'numberOfClasses': { $gt: 0 } }, { 'numberOfHours': { $gt: 0 } }, { 'numberOfMonths': { $gt: 0 } }], class: { $ne: null } })
                                                        .populate({ path: 'course', select: 'name duration' }).populate({ path: 'class' }).populate({ path: 'student' }).sort({ createdAt: -1 }).exec(function(err, courseData) {
                                                            if (courseData.length <= index) {
                                                                var xml = generateXMLMessage(fromuser, 'text', '请输入对应课程数字')
                                                                res.send(xml)
                                                            } else {
                                                                redisClient.hmset(fromuser[0], { 'leaveState': 2, student: String(theStudent._id), class: String(courseData[index].class._id) }, function(err) {
                                                                    console.log(courseData[index].class.hours, 'asjjsj')
                                                                    let message = '请选择请假时间，选择对应数字' + newLine + newLine
                                                                    let i = 0;
                                                                    let count = 0
                                                                    let hours = courseData[index].class.hours
                                                                    let today = new Date()
                                                                    let tempDay = new Date(today.getTime() + 24 * 3600000)
                                                                    while ((i < 4) && (count < 100)) {
                                                                        tempDay = new Date(tempDay.getTime() + 24 * 3600000)
                                                                        let weekday = tempDay.getDay()
                                                                        let oneIndex = hours.map(function(e) { return e.day }).indexOf(weekday)
                                                                        console.log(oneIndex, 'ddsdsd')
                                                                        if (oneIndex != -1) {
                                                                            for (let j = 0; j < hours[oneIndex].hours.length; j++) {
                                                                                let ahour = hours[oneIndex].hours[j].start
                                                                                let minxxx = ahour % 2 * 30
                                                                                let cDate = new Date(tempDay.getFullYear(), tempDay.getMonth(), tempDay.getDate(), Math.floor(ahour / 2), minxxx, 0)
                                                                                message += String(i + 1) + '.  ' + moment(cDate).format('YYYY-MM-DD HH:mm') + newLine
                                                                                i += 1
                                                                            }
                                                                        }
                                                                        count += 1

                                                                    }
                                                                    var xml = generateXMLMessage(fromuser, 'text', message)
                                                                    res.send(xml)
                                                                })

                                                            }
                                                        })
                                                }
                                            })
                                        }
                                    } else if (data.leaveState == 2) {
                                        content = content[0]
                                        if (!parseInt(content)) {
                                            var xml = generateXMLMessage(fromuser, 'text', '请输入数字')
                                            res.send(xml)
                                        } else {
                                            let index = parseInt(content) - 1
                                            let theStudent = data.student
                                            Student.findOne({ _id: theStudent }).exec(function(err, theStudent) {
                                                if (theStudent == null) {
                                                    redisClient.del(fromuser)
                                                    var xml = generateXMLMessage(fromuser, 'text', '出错了,请重试')
                                                    res.send(xml)
                                                } else {

                                                    if (content > 4) {
                                                        var xml = generateXMLMessage(fromuser, 'text', '请输入对应课程数字')
                                                        res.send(xml)
                                                    } else {
                                                        Class.findOne({ _id: data.class }).exec(function(err, classdata) {
                                                            if (classdata == null) {
                                                                redisClient.del(fromuser)
                                                                var xml = generateXMLMessage(fromuser, 'text', '出错了,请重试')
                                                                res.send(xml)
                                                            } else {

                                                                let i = 0;
                                                                let count = 0
                                                                let hours = classdata.hours
                                                                let today = new Date()
                                                                let tempDay = new Date(today.getTime() + 24 * 3600000)
                                                                let tempDates = []
                                                                while ((i < 4) && (count < 100)) {
                                                                    tempDay = new Date(tempDay.getTime() + 24 * 3600000)
                                                                    let weekday = tempDay.getDay()
                                                                    let oneIndex = hours.map(function(e) { return e.day }).indexOf(weekday)
                                                                    if (oneIndex != -1) {
                                                                        for (let j = 0; j < hours[oneIndex].hours.length; j++) {
                                                                            let ahour = hours[oneIndex].hours[j].start
                                                                            let minxxx = ahour % 2 * 30
                                                                            let cDate = new Date(tempDay.getFullYear(), tempDay.getMonth(), tempDay.getDate(), Math.floor(ahour / 2), minxxx, 0)
                                                                            tempDates.push(cDate)
                                                                            i += 1
                                                                        }
                                                                    }
                                                                    count += 1
                                                                }
                                                                let leaveDate = tempDates[content]
                                                                    // leave xxx
                                                                var newStudentLeave = new StudentLeave()
                                                                newStudentLeave.student = theStudent._id
                                                                newStudentLeave.school = classdata.school
                                                                newStudentLeave.class = classdata._id
                                                                newStudentLeave.date = leaveDate
                                                                newStudentLeave.createdAt = new Date()
                                                                newStudentLeave.isDelete = 0
                                                                newStudentLeave.status = 0
                                                                newStudentLeave.save(function(e) {
                                                                    redisClient.del(fromuser)
                                                                    var xml = generateXMLMessage(fromuser, 'text', '请假成功！')
                                                                    res.send(xml)
                                                                })
                                                            }
                                                        })

                                                    }

                                                }
                                            })
                                        }
                                    } else if (data.reportState == 0) {
                                        content = content[0]
                                        if (!parseInt(content)) {
                                            var xml = generateXMLMessage(fromuser, 'text', '请输入数字')
                                            res.send(xml)
                                        } else {
                                            WechatPublicUser.findOne({ openid: fromuser }, 'parents student cellphone').exec(function(err, wechatUser) {
                                                if (wechatUser == null) {
                                                    let xml = generateXMLMessage(fromuser, 'text', "请先绑定手机")
                                                    res.send(xml)
                                                    return false
                                                } else if (wechatUser.cellphone == null) {
                                                    let xml = generateXMLMessage(fromuser, 'text', "请先绑定手机")
                                                    res.send(xml)
                                                    return false

                                                }
                                                let index = parseInt(content) - 1
                                                Parents.find({ cellphone: wechatUser.cellphone }).exec(function(err, student) {
                                                    let students = student.map(function(e) { return e.student[0] })
                                                    if (students.length == 0) {
                                                        let xml = generateXMLMessage(fromuser, 'text', "未找到信息，请与我们联系")
                                                        res.send(xml)
                                                        return false
                                                    }
                                                    StudentStudyPlan.find({ student: students }, 'name createdAt student staff comment').populate({ path: 'student', select: 'name' }).populate('staff').sort({ 'createdAt': -1 }).skip(index).limit(1).exec(function(err, xxx) {
                                                        console.log(xxx, 'xxx', index)
                                                        if ((xxx == undefined) || (xxx.length == 0)) {
                                                            let xml = generateXMLMessage(fromuser, 'text', "未找到信息，请输入正确数字")
                                                            res.send(xml)
                                                            return false
                                                        } else {
                                                            var xml = generateXMLMessage(fromuser, 'text', xxx[0].comment)
                                                            redisClient.del(fromuser)
                                                            res.send(xml)
                                                        }

                                                    })
                                                })
                                            })




                                        }
                                    } else {

                                    }
                                } else {
                                    var xml = generateXMLMessage(fromuser, 'text', '如需绑定手机请点击绑点手机，如需帮助请点击联系我们')
                                    res.send(xml)
                                    return false
                                }
                            })
                        }
                    }
                })
            })
        })
    },



    rollcallModel: async(studentId, staffId, className, status) => {
        return rollcallModel(studentId, staffId, className, status)
    },
    balance: async(studentId, paid) => {
        return balance(studentId, paid)
    },
    newPlan: async(studentId, staffId) => {
        return newPlan(studentId, staffId)
    }
}

function generateXMLMessage(user, type, content) {
    var temp = '<xml>'
    temp += '<ToUserName><![CDATA[' + user + ']]></ToUserName>'
    temp += '<FromUserName><![CDATA[' + account + ']]></FromUserName>'
    temp += '<CreateTime><![CDATA[' + new Date().getTime() + ']]></CreateTime>'
    temp += '<MsgType><![CDATA[' + type + ']]></MsgType>'
    temp += '<Content><![CDATA[' + content + ']]></Content>'
    temp += '</xml>'
    return temp
}

function getToken(callback) {

    redisClient.get('access_token', function(err, data) {
        if (data == null || data == 'undefined') {

            callback(getAccessTokenFromWeb(function(e) {}))
        } else {
            console.log('had', data)
            callback(data)
        }

    })
}


function newPlan(studentId, staffId) {
    getToken(function(access_token) {
        Staff.findOne({ _id: staffId }, 'name').exec(function(err, staff) {
            console.log(staff, 'dskkdsk', staffId)
            Student.findById(studentId, 'name').populate({ path: 'school', select: 'name' }).exec(function(err, student) {
                Parents.find({ student: studentId }, 'student cellphone').populate('student').exec(function(err, parents) {
                    if (parents.length != 0) {
                        WechatPublicUser.find({ cellphone: { $in: parents.map(function(e) { return e.cellphone }) } }).exec(function(err, xdata) {
                            if (xdata != undefined) {
                                xdata.forEach(value => {
                                    let url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token
                                    let data = {}
                                    data.touser = value.openid
                                    data.template_id = "VXPVFZyLd6AMxnGmUwQXBKOYtqNbkPmwu22V-Vf0Trk"
                                    data.data = {
                                        "first": {
                                            "value": "家长您好！您的孩子有了一份新的学习报告。",
                                            "color": "#173177"
                                        },
                                        "keyword1": {
                                            "value": student.name,
                                            "color": "#173177"
                                        },
                                        "keyword2": {
                                            "value": new moment().format('YYYY-MM-DD HH:mm') + ', 请去服务号查看',
                                            "color": "#173177"
                                        },
                                        "keyword3": {
                                            "value": staff.name,
                                            "color": "#173177"
                                        },


                                        "remark": {
                                            "value": '请去服务号查看',
                                            "color": "#173177"
                                        }
                                    }
                                    request({
                                        url: url,
                                        method: "POST",
                                        timeout: 10000,
                                        body: data,
                                        followRedirect: true,
                                        json: true,
                                        maxRedirects: 10
                                    }, function(error, res, req) {
                                        console.log(req, 'dsdss')
                                        if (req.errcode == 40001) {
                                            getAccessTokenFromWeb(function(token) {
                                                newPlan(studentId, staffId)
                                            })
                                        }
                                    })
                                })
                            }
                        })
                    }
                })
            })
        })
    })
}


function rollcallModel(studentId, staffId, className, status) {
    getToken(function(access_token) {
        Staff.findOne({ _id: staffId }, 'name').exec(function(err, staff) {
            Student.findById(studentId, 'name').exec(function(err, student) {
                Parents.find({ student: studentId }, 'student cellphone').populate('student').exec(function(err, parents) {
                    if (parents.length != 0) {
                        WechatPublicUser.find({ cellphone: { $in: parents.map(function(e) { return e.cellphone }) } }).exec(function(err, xdata) {
                            if (xdata != undefined) {
                                xdata.forEach(value => {
                                    let url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token
                                    let data = {}
                                    data.touser = value.openid
                                    data.template_id = "BiCuM-_phmOj-xA_uAuMSlTR-hr6JSQTj5bLbLAneVo"
                                    data.data = {
                                        "first": {
                                            "value": "家长您好！您有一条签到信息。",
                                            "color": "#173177"
                                        },
                                        "keyword1": {
                                            "value": student.name,
                                            "color": "#173177"
                                        },
                                        "keyword2": {
                                            "value": className,
                                            "color": "#173177"
                                        },
                                        "keyword3": {
                                            "value": new moment().format('YYYY-MM-DD HH:mm'),
                                            "color": "#173177"
                                        },
                                        "keyword4": {
                                            "value": status == 0 ? '点名成功' : '确认缺席',
                                            "color": "#173177"
                                        },
                                        "keyword5": {
                                            "value": staff.name,
                                            "color": "#173177"
                                        },
                                        "remark": {
                                            "value": status == 0 ? "正在努力学习中！" : '缺席课程',
                                            "color": "#173177"
                                        }
                                    }
                                    request({
                                        url: url,
                                        method: "POST",
                                        timeout: 10000,
                                        body: data,
                                        followRedirect: true,
                                        json: true,
                                        maxRedirects: 10
                                    }, function(error, res, req) {
                                        if (req.errcode == 40001) {
                                            getAccessTokenFromWeb(function(token) {
                                                rollcallModel(studentId, staffId, className, status)
                                            })
                                        }
                                    })
                                })
                            }
                        })
                    }
                })
            })
        })
    })
}


function balance(studentId, paid) {
    getToken(function(access_token) {
        Student.findById(studentId, 'name payType credit remainingHours').exec(function(err, student) {
            Parents.find({ student: { $in: studentId } }, 'student').populate('student').exec(function(err, parents) {
                if (parents.length != 0) {
                    WechatPublicUser.findOne({ parents: parents[0]._id }, 'openid').exec(function(err, user) {
                        let url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token
                        let remaining = ""
                        if (student.payType == 0) {
                            remaining = student.credit + "元"
                            paid = paid + "元"
                        } else if (student.payType == 1) {
                            remaining = student.remainingHours + "小时"
                            paid = paid + "小时"
                        }
                        if (user != null) {
                            let data = {}
                            data.touser = user.openid
                            data.template_id = "mOe4uLPWYOSNEohClaWqZbiUU9qxZe_xxsH2D6zwFw0"
                            data.data = {
                                "first": {
                                    "value": "余额提醒!",
                                    "color": "#173177"
                                },
                                "keyword1": {
                                    "value": paid,
                                    "color": "#173177"
                                },
                                "keyword2": {
                                    "value": "扣费事由",
                                    "color": "#173177"
                                },
                                "keyword3": {
                                    "value": remaining,
                                    "color": "#173177"
                                },
                                "keyword4": {
                                    "value": new moment().format('YYYY-MM-DD'),
                                    "color": "#173177"
                                },
                                "remark": {
                                    "value": "余额已经不足！",
                                    "color": "#173177"
                                }
                            }
                            request({
                                url: url,
                                method: "POST",
                                timeout: 10000,
                                body: data,
                                followRedirect: true,
                                json: true,
                                maxRedirects: 10
                            }, function(error, res, req) {})
                        }
                    })
                }
            })
        })
    })
}

function getUserInfo(openid) {
    getToken(function(token) {
        console.log(token, openid)
        let url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + token + "&openid=" + openid + "&lang=zh_CN"
        request({
            url: url,
            method: "GET",
            timeout: 10000,
            followRedirect: true,
            maxRedirects: 10
        }, function(error, res, req) {
            let userInfo = JSON.parse(req)
            console.log(userInfo, 'userInfo')
            if (userInfo.errcode != undefined) {
                getAccessTokenFromWeb(function(e) {})
            }
            let wechatUser = new WechatPublicUser({
                openid: userInfo.openid,
                gender: userInfo.sex,
                city: userInfo.city,
                province: userInfo.province,
                country: userInfo.country,
                avatar: userInfo.headimgurl,
                nickName: userInfo.nickName,
                unionid: userInfo.unionid,
                isDelete: 0,
                createdAt: new Date(),
            })
            wechatUser.save()
        })
    })
}

//如果错误码 40014 直接调用该函数,待fix
function getAccessTokenFromWeb(callback) {
    console.log(appID, appsecret)
    var wxurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appID + "&secret=" + appsecret
    request({
        url: wxurl,
        method: "GET",
        timeout: 10000,
        followRedirect: true,
        maxRedirects: 10
    }, function(error, response, body) {
        console.log(error, body, 'dd')
        redisClient.set('access_token', JSON.parse(body).access_token, function(err, success) {
            redisClient.expire('access_token', parseInt(JSON.parse(body).expires_in), function(err, ress) {
                callback(JSON.parse(body).access_token)
            })
        })
    })
}


function createMenu(access_token) {
    var url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=' + access_token
    redisClient.get('tagId', function(err, id) {
        let tagId = id || ''
        var data = {
            "button": [{
                    "name": "学生信息",
                    "sub_button": [{
                            "type": "click",
                            "name": "班级情况查询",
                            "key": "classDetail"
                        },
                        {
                            "type": "click",
                            "name": "上课情况查询",
                            "key": "rollCallDetail"
                        },
                        {
                            "type": "click",
                            "name": "剩余课时查询",
                            "key": "remainder"
                        },
                        {
                            "type": "click",
                            "name": "上课请假",
                            "key": "askLeave"
                        },
                        {
                            "type": "click",
                            "name": "学习报告",
                            "key": "report"
                        }
                    ]
                },
                {
                    "name": "学校介绍",
                    "sub_button": [{
                            "type": "click",
                            "name": "历史文章",
                            "key": "history"
                        },
                        {
                            "type": "click",
                            "name": "联系我们",
                            "key": "contactUs"
                        }
                    ]
                },
                {
                    "name": '手机绑定',
                    "key": 'cellphone_bind',
                    'type': 'click'
                }


            ],
            "matchrule": {
                "tag_id": 1
            }
        }
        request({
            url: url,
            method: "POST",
            timeout: 10000,
            body: data,
            followRedirect: true,
            json: true,
            maxRedirects: 10
        }, function(error, res, req) {
            console.log('blah3 ', req)

        })
    })
}

function creatConditionalMenu(access_token) {
    var url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=' + access_token
    redisClient.get('tagId', function(err, id) {
        let tagId = id || ''
        var data = {
            "button": [{
                    "name": "学生信息",
                    "sub_button": [{
                            "type": "click",
                            "name": "班级情况查询",
                            "key": "classDetail"
                        },
                        {
                            "type": "click",
                            "name": "上课情况查询",
                            "key": "rollCallDetail"
                        },
                        {
                            "type": "click",
                            "name": "剩余课时查询",
                            "key": "remainder"
                        },
                        {
                            "type": "click",
                            "name": "上课请假",
                            "key": "askLeave"
                        },
                        {
                            "type": "click",
                            "name": "学习报告",
                            "key": "report"
                        }
                    ]
                },
                {
                    "name": "学校介绍",
                    "sub_button": [{
                            "type": "click",
                            "name": "历史文章",
                            "key": "history"
                        },
                        {
                            "type": "click",
                            "name": "联系我们",
                            "key": "contactUs"
                        }
                    ]
                },
                {
                    "name": '手机绑定',
                    "key": 'cellphone_bind',
                    'type': 'click'
                }


            ],
            "matchrule": {
                "tag_id": 1
            }
        }
        request({
            url: url,
            method: "POST",
            timeout: 10000,
            body: data,
            followRedirect: true,
            json: true,
            maxRedirects: 10
        }, function(error, res, req) {
            console.log('blah2 ', req)

        })
    })
}

function validateCellphone(cellphone) {
    if (parseInt(cellphone) != undefined) {
        console.log('sddsds', cellphone.length)
        if (String(cellphone).length == 11) {
            console.log('dsads')
            return true
        }
    }
    return false
}

function creatValidateCellphoneCode() {
    var sixdigitnumber = Math.floor((Math.random() * 900000) + 100000 - 1);
    return parseInt(sixdigitnumber)
}

// function getTags(accessToken) {
//     let creatUrl = "https://api.weixin.qq.com/cgi-bin/tags/create?access_token=" + accessToken
//     let data = { "tag": { "name": "手机已绑定" } }
//     request({
//         url: creatUrl,
//         method: "POST",
//         timeout: 10000,
//         body: data,
//         followRedirect: true,
//         json: true,
//         maxRedirects: 10
//     }, function (error, res, data) {
//         if (data.errcode == 45157) {
//             let url = "https://api.weixin.qq.com/cgi-bin/tags/get?access_token=" + accessToken
//             request({
//                 url: url,
//                 method: "GET",
//                 timeout: 10000,
//                 followRedirect: true,
//                 maxRedirects: 10
//             }, function (error, res, req) {
//                 let tags = JSON.parse(req).tags
//                 for (let i = 0; i < tags.length; i++) {
//                     if (tags[i].name == "手机已绑定") {
//                         redisClient.set('tagId', tags[i].id)
//                     }
//                 }
//             })
//         } else {
//             redisClient.set('tagId', tags[i].id)
//         }
//     })
// }

// function remainingModel(openid, accessToken) {
//     let url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken
//     let data = {}
//     data.touser = openid[0]
//     data.template_id = "dR59WNyw2QVQnfRfbXmB2D0SQUjYLkP8bBPE95SEmrs"
//     data.data = {
//         "result": {
//             "value": "剩余课时提醒",
//             "color": "#173177"
//         },
//         "date": {
//             "value": date,
//             "color": "#173177"
//         },
//         "name": {
//             "value": name,
//             "color": "#173177"
//         },
//         "remaining": {
//             "value": remaining,
//             "color": "#173177"
//         },
//         "remark": {
//             "value": "希望继续选择我们！",
//             "color": "#173177"
//         }
//     }
//     request({
//         url: url,
//         method: "POST",
//         timeout: 10000,
//         body: data,
//         followRedirect: true,
//         json: true,
//         maxRedirects: 10
//     }, function (error, res, req) {
//     })
// }